import React, { useState, useEffect } from 'react';
import { Edit } from 'lucide-react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';

const FileRenameDialog = ({ open, onOpenChange, file, onRename }) => {
  const [newName, setNewName] = useState('');
  const [isRenaming, setIsRenaming] = useState(false);

  useEffect(() => {
    if (file && open) {
      setNewName(file.name);
    }
  }, [file, open]);

  const handleConfirm = async () => {
    if (!newName || !newName.trim() || newName === file.name) {
      return;
    }

    setIsRenaming(true);
    try {
      await onRename(file, newName.trim());
      onOpenChange(false);
    } catch (error) {
      console.error('重命名失败:', error);
    } finally {
      setIsRenaming(false);
    }
  };

  const handleKeyPress = (e) => {
    if (e.key === 'Enter') {
      handleConfirm();
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle className="flex items-center space-x-2">
            <Edit className="w-5 h-5" />
            <span>重命名</span>
          </DialogTitle>
        </DialogHeader>
        <div className="space-y-4">
          <div>
            <Label htmlFor="newName">新名称</Label>
            <Input
              id="newName"
              value={newName}
              onChange={(e) => setNewName(e.target.value)}
              onKeyPress={handleKeyPress}
              placeholder={`请输入新的${file?.isDirectory ? '目录' : '文件'}名`}
              autoFocus
            />
          </div>
          {file && (
            <div className="text-sm text-material-grey-600">
              <p>当前名称：{file.name}</p>
              <p className="mt-1">类型：{file.isDirectory ? '目录' : '文件'}</p>
            </div>
          )}
        </div>
        <DialogFooter>
          <Button 
            variant="outline" 
            onClick={() => onOpenChange(false)}
            disabled={isRenaming}
          >
            取消
          </Button>
          <Button 
            onClick={handleConfirm}
            disabled={isRenaming || !newName.trim() || newName === file?.name}
          >
            {isRenaming ? (
              <>
                <div className="w-4 h-4 mr-2 border-2 border-white border-t-transparent rounded-full animate-spin" />
                重命名中...
              </>
            ) : (
              '确定'
            )}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};

export default FileRenameDialog;
